import subprocess

def run_adb_command():
    # Step 1: 检查设备连接状态
    try:
        print("检查设备连接状态...")
        result = subprocess.run(["adb", "devices"], capture_output=True, text=True, encoding="utf-8")
        if "device" not in result.stdout.strip().split("\n")[-1]:
            print("未检测到设备，请检查设备连接。")
            return
    except Exception as e:
        print(f"检查设备时出错：{e}")
        return

    # Step 2: 通过 adb shell 执行 dumpWindowHierarchy 命令
    curl_command = (
        'curl -X POST '
        '-H "Content-Type: application/json" '
        '-d \'{"jsonrpc": "2.0", "method": "dumpWindowHierarchy", "params": [true], "id": 1}\' '
        'http://127.0.0.1:9009/jsonrpc/0'
    )

    print("通过 adb shell 执行 dumpWindowHierarchy 命令获取窗口xml信息...")
    try:
        result = subprocess.run(
            ["adb", "shell", curl_command],
            capture_output=True,
            text=True,
            encoding="utf-8"  # 指定使用 UTF-8 解码
        )
        # 输出命令返回的结果
        if result.returncode == 0:
            print("命令执行成功，返回结果如下：")
            print(result.stdout)
        else:
            print("命令执行失败，错误信息如下：")
            print(result.stderr)
    except UnicodeDecodeError as ude:
        print(f"Unicode 解码错误：{ude}")
    except Exception as e:
        print(f"执行命令时出错：{e}")

if __name__ == "__main__":
    run_adb_command()
    input("按回车键退出程序...")
